package com.kool.kmqtt.server.parser;

import com.kool.kmqtt.server.packet.FixedHeader;
import com.kool.kmqtt.server.packet.SubscribeVariableHeader;
import com.kool.kmqtt.server.packet.UnsubscribePayload;
import io.netty.buffer.ByteBuf;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * UNSUBSCRIBE报文解析器
 */
public class UnsubscribePacketParser extends PacketParser {
    public UnsubscribePacketParser(FixedHeader fixedHeader) {
        super(fixedHeader);
    }

    @Override
    public void parseVariableHeader(ByteBuf in) {
        SubscribeVariableHeader variableHeader = new SubscribeVariableHeader();
        byte packetIdMSB = in.readByte();
        byte packetIdLSB = in.readByte();
        //报文标识
        int packetId = (Byte.toUnsignedInt(packetIdMSB) << 8) + Byte.toUnsignedInt(packetIdLSB);
        variableHeader.setPacketId(packetId);
        packet.setPacketId(packetId);
        packet.setVariableHeader(variableHeader);
        packet.setVariableHeaderLength(2);
    }

    @Override
    public void parsePayload(ByteBuf in) {
        List<String> topicFilters = new ArrayList<>();

        int index = 0;
        while (index < packet.getFixedHeader().getRemainingLength() - packet.getVariableHeaderLength()) {
            byte topicFilterLengthMSB = in.readByte();
            byte topicFilterLengthLSB = in.readByte();
            int topicFilterLength = (Byte.toUnsignedInt(topicFilterLengthMSB) << 8) + Byte.toUnsignedInt(topicFilterLengthLSB);

            ByteArrayOutputStream topicFilterBytesArray = new ByteArrayOutputStream();
            for (int i = 0; i < topicFilterLength; i++) {
                topicFilterBytesArray.write(in.readByte());
            }
            //主题过滤器
            String topicFilter = new String(topicFilterBytesArray.toByteArray(), StandardCharsets.UTF_8);
            topicFilters.add(topicFilter);

            index = index + 2 + topicFilterLength;
        }

        UnsubscribePayload payload = new UnsubscribePayload();
        payload.setTopicFilters(topicFilters);

        packet.setPayload(payload);
    }
}
